require 'View/UIBase/UIBase'

UIChapterReward = UIBase.New(PanelNames.UIChapterReward,UIBase)

function UIChapterReward.Init(func)
    UIBase.Init(UIChapterReward,func);
end

-- 创建回调
function UIChapterReward:OnCreate()
    self.title = self:GetChild("tltle");
    self.title.text = getLanguage("ChapterRewardTips1");
    self.tips = self:GetChild("tips");
    self.tips.text = getLanguage("ChapterRewardTips2");
    self.itemList = self:SetDynamicList(self:GetChild("list"),self.updateItem)
    self:addEvent();
end

-- 显示
function UIChapterReward:OnEnable()
    self:Refresh();
end

function UIChapterReward:addEvent()
    self:RegisterOnClick(self:GetChild("bgClose"),self.OnClose)
end

function UIChapterReward:removeEvent()
end

function UIChapterReward:Refresh()
    self.taskConfig = logicMgr.TaskManager.getRemarkShowDataByType(EnumConst.AchieveTaskType.Custom);
    self.showData = {};
    if #self.taskConfig > 0 then
        table.sort(self.taskConfig, function(a, b)
            return a.f_TaskId < b.f_TaskId
        end);
        self.nowTaskTable = {};
        self.nowTaskTable.f_PostTaskId = self.taskConfig[1].f_TaskId;
        self.nowMapTable = logicMgr.MapManager.getMapcfg();
        if self.nowMapTable == nil then
            logError("找不到当前关卡");
            self:OnClose();
            return ;
        end
        self.nowChapter = self.nowMapTable.f_ChapterId;
        self.nowChapterCount = logicMgr.MapManager.getMapStageNumById(self.nowMapTable.f_StageId);
        while self.nowTaskTable.f_PostTaskId ~= 0 do
            self.nowTaskTable = logicMgr.TaskManager.getTaskTableData(self.nowTaskTable.f_PostTaskId);
            self.curTable = logicMgr.MapManager.GetMapcfgByID(self.nowTaskTable.f_Progress);
            if self.curTable ~= nil then
                if self.curTable.f_ChapterId > self.nowChapter + 1 then
                    break;
                end
                local data = {};
                data.reward = decodeJsonStrToTabel(self.nowTaskTable.f_Award);
                data.num = getLanguage(self.nowTaskTable.f_TaskDesc);
                table.insert(self.showData, data);
            end
        end
    end
    self:UpdateData();
end

function UIChapterReward:UpdateData()
    self.itemList.numItems = #self.showData;
end

function UIChapterReward:updateItem(index, itemObj)
    local curData = self.showData[index];
    if curData == nil then
        itemObj.visible = false;
        return;
    end
    itemObj.visible = true;
    local title = itemObj:GetChild("title");
    local rewardList = itemObj:GetChild("rewardList");
    title.text = curData.num;
    logicMgr.CostManager.RefreshItemList(rewardList, curData.reward, nil, {isShowBigNum=true});
end

-- 关闭
function UIChapterReward:OnClose()
    self:OnBack();
end

-- 隐藏
function UIChapterReward:OnDisable()
end

-- 卸载
function UIChapterReward:OnDestroy()
    self:removeEvent();
end

return UIChapterReward